<template>
    <div class="product-management">
        <h2>商品管理</h2>
        <button @click="openAddModal"
            style="padding: 5px 10px; margin-bottom: 10px;border: 1px solid #ccc; border-radius: 5px;">添加商品</button>
        <table>
            <thead>
                <tr>
                    <th>商品图片</th>
                    <th>商品名称</th>
                    <th>描述</th>
                    <th>商品类型</th>
                    <th style="text-align: center;">单价</th>
                    <th style="text-align: center;">库存</th>
                    <th style="text-align: center;">操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="product in products" :key="product.productId">
                    <td>
                        <img :src="product.imageUrl" alt="商品图片" class="product-image" />
                    </td>
                    <td>{{ product.name }}</td>
                    <td style="color: #666; font-size: 14px;">{{ product.description }}</td>
                    <td style="width: 70px; text-align: center;">{{ product.sort }}</td>
                    <td style="width: 70px; text-align: center;">{{ product.price }}</td>
                    <td style="width: 40px; text-align: center;">{{ product.stock }}</td>
                    <td style="width: 40px; text-align: center;">
                        <button
                            style="margin-bottom: 20px;padding: 5px 10px; border: 1px solid #ccc; border-radius: 5px;"
                            @click="openEditModal(product)">编辑</button>
                        <button style="padding: 5px 10px; border: 1px solid #ccc; border-radius: 5px;"
                            @click="deleteProduct(product.productId)">删除</button>
                    </td>
                </tr>
            </tbody>
        </table>

        <!-- 分页控件 -->
        <div class="pagination">
            <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
            <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
            <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
        </div>

        <!-- 添加/编辑商品模态弹窗 -->
        <div v-if="showModal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeModal">&times;</span>
                <h2>{{ isEdit ? '编辑商品' : '添加商品' }}</h2>
                <form @submit.prevent="isEdit ? updateProduct() : addProduct()">
                    <input v-model="currentProduct.name" placeholder="商品名称" required />
                    <input v-model="currentProduct.description" placeholder="描述" required />
                    <input v-model.number="currentProduct.price" placeholder="单价" type="number" required />
                    <input v-model.number="currentProduct.stock" placeholder="库存" type="number" required />
                    <input v-model="currentProduct.imageUrl" placeholder="图片链接" required />
                    <input v-model="currentProduct.sort" placeholder="商品类型" required />
                    <button type="submit">{{ isEdit ? '更新' : '添加' }}</button>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { get, post } from "../until/request";
import Swal from 'sweetalert2';

const products = ref([]);   // 商品列表
const showModal = ref(false);  // 是否显示模态框
const isEdit = ref(false);   // 是否编辑
const currentProduct = ref({});  // 当前商品
const currentPage = ref(1);   // 当前页
const totalPages = ref(1);  // 总页数
const pageSize = 3; // 每页显示的商品数量

onMounted(async () => {
    await fetchProducts();
});

// 获取商品列表
async function fetchProducts() {
    const response = await get(`/admin/productList?page=${currentPage.value}&size=${pageSize}`);
    if (response.code === 1) {
        products.value = response.data.list;
        totalPages.value = response.data.pages;
    }
}

// 上一页
function prevPage() {
    if (currentPage.value > 1) {
        currentPage.value--;
        fetchProducts();
    }
}

// 下一页
function nextPage() {
    if (currentPage.value < totalPages.value) {
        currentPage.value++;
        fetchProducts();
    }
}

// 打开添加商品模态框
function openAddModal() {
    currentProduct.value = {};
    isEdit.value = false;
    showModal.value = true;
}

// 打开编辑商品模态框
function openEditModal(product) {
    currentProduct.value = { ...product };
    isEdit.value = true;
    showModal.value = true;
}

// 添加商品
async function addProduct() {
    const response = await post('/admin/addProduct', currentProduct.value);
    if (response.code === 1) {
        await fetchProducts();  // 重新获取商品列表
        closeModal();           // 关闭模态框
        Swal.fire({
            title: '成功',
            text: '添加商品成功',
            icon: 'success',
        });
    } else {
        Swal.fire({
            title: '失败',
            text: response.message,
            icon: 'error',
        });
    }
}

// 更新商品
async function updateProduct() {
    const response = await post('/admin/updateProduct', currentProduct.value);
    if (response.code === 1) {
        await fetchProducts();  // 重新获取商品列表
        closeModal();           // 关闭模态框
        Swal.fire({
            title: '成功',
            text: '更新商品成功',
            icon: 'success',
        });
    } else {
        Swal.fire({
            title: '失败',
            text: response.message,
            icon: 'error',
        });
    }
}

// 删除商品
async function deleteProduct(productId) {
    const response = await get(`/admin/deleteProduct?productId=${productId}`);
    if (response.code === 1) {
        await fetchProducts();  // 重新获取商品列表
        Swal.fire({
            title: '成功',
            text: '删除商品成功',
            icon: 'success',
        });
    } else {
        Swal.fire({
            title: '失败',
            text: response.message,
            icon: 'error',
        });
    }
}

// 关闭模态框
function closeModal() {
    showModal.value = false;
}
</script>

<style scoped>
.product-management {
    padding: 0 20px 20px 20px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

button {
    margin-right: 5px;
}

.modal {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
}

.modal-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    width: 400px;
    position: relative;
}

.close {
    position: absolute;
    top: 10px;
    right: 20px;
    font-size: 24px;
    cursor: pointer;
}

form input {
    display: block;
    width: 100%;
    margin-bottom: 10px;
    padding: 8px;
    box-sizing: border-box;
}

.product-image {
    max-width: 100px;
    height: auto;
    display: block;
    margin: 0 auto;
}

.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
}

.pagination button {
    margin: 0 10px;
}
</style>